package hxg.thread.readwritelock;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author HeXiangGuang
 * @create 2021-06-24 18:30
 */
public class TestReadWriteDemo {
    public static void main(String[] args) {
        ReadWriteDemo readWriteDemo = new ReadWriteDemo();
        //创建线程池
        ExecutorService es = Executors.newFixedThreadPool(20);
        Runnable read = new Runnable(){

            @Override
            public void run() {
                try {
                    readWriteDemo.getValue();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Runnable write = new Runnable(){

            @Override
            public void run() {
                try {
                    readWriteDemo.setValue("张三"+new Random().nextInt(100));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        long start = System.currentTimeMillis();

        for (int i = 0; i < 2; i++) {
            es.submit(write);
        }
        for (int i=0;i<18;i++){
            es.submit(read);
        }
        es.shutdown();
        //空转，意思是写个死循环放在这里等所有线程执行结束在跳出死循环
        //main方法使主线程，然后当开启子线程后main方法还会继续往下执行，子线程是并发运行的。
        System.out.println("程序开启子线程之后----程序开始空转等线程池线程运行完毕");
        while (!es.isTerminated()){

        }
        long end = System.currentTimeMillis();
        System.out.println("用时"+(end-start));
    }
}
